#!/usr/bin/env python

import os
import sys
import re
#from barchart import *
import numpy as np

def usage():
    print '''\
Usage: %s -s <stats>
''' % sys.argv[0]
    sys.exit(1)

def getopts(list, flags):
    import getopt
    try:
        opts, args = getopt.getopt(list, flags)
    except getopt.GetoptError:
        usage()

    return opts, args

result_dir1 = '/export/homeO5/pengfei/spec_workdir/results/trips/linux'
conf = 'atomic-fast-mem'
#conf = 'simple-normal-cache'
result_dir2 = '/export/homeO5/pengfei/spec_workdir/figs/lotus'
ref_file = 'sim.cycles.stat'

output_dir = '/export/homeO5/pengfei/spec_workdir/figs'
stats_file = '%s.stat.%s'
variant = 'test'
line_template = '%s & %f & %f & %f' # For latex table
line_template1 = '%s & %f & %f & %f' # For latex table
clock = 500.0

#benchmarks = ['gzip','vpr','gcc','mcf',
#              'crafty','parser','vortex','bzip2','twolf',
#              'wupwise','swim','mgrid','applu',
#              'mesa','art','equake','ammp',
#              'apsi']

benchmarks = os.listdir(result_dir1 + '/' + variant)
benchmarks.sort()
benchmarks.remove('gap')
#conf1 = 'simple-normal-cache-double-fetch-hyperblock'
#conf1 = 'simple-fastMem-double-fetch'
#conf1 = 'simple-fastMem-double-fetch-hyperblock'
#conf2 = 'simple-fastMem-double-fetch-hyperblock'
#conf2 = 'simple-fastMem'

class VecStat(object):
    stat = np.zeros(5)
    refname = 'ref'
    def __init__(self,bname,sname,**kwargs):
        self.bname = bname
        self.sname = sname
        self.refname = rname
        stats_file = result_dir + '/' + bname + '/' + config + '/'  +  'stats.txt'
	for line in open(stats_file):
	    l = line.split()
	    if not l:
	        continue
	    if l[0] == bname and l[1] == sname:
	        for i, stat in enumerate(l):
	            if i > 1:
	                if i > 2:
	                    self.stat[i-2] =float( l[i])-float(l[i-1])
	                else:
	                    self.stat[i-2] = float(l[i])
		break
    
    def data(self):
        return self.stat

    def refname(self):
        return self.refname

class RefStat(object):
    stat = float(0)
    def __init__(self,bname,**kwargs):
        self.bname = bname
        stats_file = result_dir2 + '/' + ref_file
	for line in open(stats_file):
	    l = line.split('\t')
	    if not l:
	        continue
	    if l[0] == bname:
	        self.stat = float(l[1])
		break
    
    def data(self):
        return self.stat

    def refname(self):
        return self.refname
        
class Stat(object):
    stat = float(0)
    def __init__(self,bname,sname,variant,**kwargs):
        self.bname = bname
        self.sname = sname
        stats_file = result_dir1 + '/' + variant + '/' + bname + '/' + conf + '/'  +  'stats.txt'
	for line in open(stats_file):
	    l = line.split()
	    if not l:
	        continue
	    if l[0] == sname:
	        self.stat = float(l[1])
		break
    
    def data(self):
        return self.stat

class FunnyStat(object):
    stat = float(0)
    def __init__(self,bname,s1name,s2name,config,**kwargs):
        self.bname = bname
        self.s1name = s1name
        self.s2name = s2name
        stats_file = result_dir + '/' + bname + '/' + config + '/'  +  'stats.txt'
	for line in open(stats_file):
	    l = line.split()
	    if not l:
	        continue
	    if l[0] == s1name and l[1] == s2name:
	        self.stat = float(l[2])
		break
    
    def data(self):
        return self.stat

class Options:pass

if __name__ == '__main__':
    import getpass

    options = Options()
    options.stats = None
    options.type = None
   
    opts, args = getopts(sys.argv[1:],'-s:t:')

    for o,a in opts:
        if o == '-s':
            options.stats = a.split(',')
	if o == '-t':
	    options.type = a

    if not options.stats:
        sys.exit('Stats must be provided by -s')

    print options.stats
    data_store = np.zeros(len(benchmarks)*len(options.stats))
    data_store.shape = (len(benchmarks), len(options.stats))
    result = np.zeros(len(benchmarks))
    #print options.stats
    #stat_num = len(options.stats)
    #print stat_num
    #if stat_num != 2:
    #    print >>stderr,'Two stats are required'
    #    sys.exit(1)
    stats_file = stats_file % ('avg',conf)
    output_file = file(output_dir + '/' + stats_file, 'w')
    print >>output_file,"Benchmarks & %s & %s & Kilo insts per sec" %\
        (options.stats[0],options.stats[1])
    if options.type == 'avg':
        for j,stat in enumerate(options.stats):
            #stats_file = stats_file % (stat,conf)
            for i,bench in enumerate(benchmarks):
                s1 = Stat(bench,stat,variant)
                data1 = s1.data()
	        data_store[i,j] = data1
        for i,bench in enumerate(benchmarks):
	    result[i] = data_store[i,0] / data_store[i,1]
	    print >>output_file, line_template1 % (bench,data_store[i,0],data_store[i,1],result[i]/1000.0)
	print 'Avg:'
	avg = (result.sum() / len(benchmarks))
	print avg/1000.0
	print >>output_file,('Avg & %f' % (avg / 1000.0))
        output_file.close()
	sys.exit(0)
    
    for stat in options.stats:
        stats_file = stats_file % (stat,conf)
        output_file = file(output_dir + '/' + stats_file, 'w')
	print >>output_file,'Benchmarks & m5\\_edge & tsim\\_proc & Diff \\\\'
        for i,bench in enumerate(benchmarks):
            s1 = Stat(bench,stat,variant)
	    s2 = RefStat(bench)
            data1 = s1.data()
	    data1 = data1 / clock
	    data2 = s2.data()
	    diff = (data1 - data2) / data1
	    print diff
            line = line_template % (bench,data1,data2,(diff * 100)) 
	    line = line + '\% \\\\' # For latex table
            print >>output_file,line 
	    print >>output_file,'\\hline'
        output_file.close()

    
